//
//  ScrollViewCell.m
//  LoveHealth
//
//  Created by 陈永坤 on 14-9-21.
//  Copyright (c) 2014年 lanou. All rights reserved.
//

#import "ScrollViewCell.h"
#import "UIImageView+WebCache.h"
@interface ScrollViewCell ()


@property (nonatomic,retain) NSTimer * timer;

//计时器
- (void)p_startTimer;

//延展中定义布局子视图
- (void)p_setupSubviews;
//设置scrollView上图片自动滚动的时间间隔
- (void)p_setupTimeForScrollView;

@end


@implementation ScrollViewCell

- (void)dealloc
{

    self.scrollView = nil;
    self.firstImageView = nil;
    self.secondImageView = nil;
    self.thirdImageView = nil;
    self.pageControl = nil;
    self.firstLabel = nil;
    self.secondLabel = nil;
    self.thirdLabel = nil;
    self.imageViewArray = nil;
    self.healthNewsArray = nil;
    Block_release(_pushDetailViewBock);
    [super dealloc];
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        [self p_setupSubviews];
    }
    return self;
}

//延展中定义布局子视图
- (void)p_setupSubviews
{
   
    //创建滚动视图
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 140)];
    _scrollView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:_scrollView];
    //滚动的范围
    _scrollView.contentSize = CGSizeMake(self.bounds.size.width * 3, 140);
    //分页滑动
    _scrollView.pagingEnabled = YES;
    //设代理
    _scrollView.delegate = self;
    //_scrollView.userInteractionEnabled = YES;
    
    //第一张图片
    _firstImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 140)];
    _firstImageView.backgroundColor = [UIColor clearColor];
    [_scrollView addSubview:_firstImageView];
    _firstImageView.userInteractionEnabled = YES;
    _firstImageView.contentMode = UIViewContentModeScaleAspectFill;
    _firstImageView.clipsToBounds = YES;
    //第二张图片
    _secondImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.bounds.size.width, 0, self.bounds.size.width, 140)];
    _secondImageView.backgroundColor = [UIColor clearColor];
    [_scrollView addSubview:_secondImageView];
    _secondImageView.userInteractionEnabled = YES;
    _secondImageView.contentMode = UIViewContentModeScaleAspectFill;
    _secondImageView.clipsToBounds = YES;
    
    //第三张图片
    _thirdImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.bounds.size.width * 2, 0, self.bounds.size.width, 140)];
    _thirdImageView.backgroundColor = [UIColor clearColor];
    [_scrollView addSubview:_thirdImageView];
    _thirdImageView.userInteractionEnabled = YES;
    _thirdImageView.contentMode = UIViewContentModeScaleAspectFill;
    _thirdImageView.clipsToBounds = YES;
    
    //添加三个imageView
    self.imageViewArray = @[_firstImageView,_secondImageView,_thirdImageView];
    //分别为imageView添加手势
    [self addTapGesture];

    
    //分页控制
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(self.bounds.size.width - 60, 100, 60, 20)];
    //添加到根视图上
    [self addSubview:_pageControl];
    _pageControl.pageIndicatorTintColor = [UIColor grayColor];
    _pageControl.currentPageIndicatorTintColor = UIColorCommon;
    
    //页数
    _pageControl.numberOfPages = 3;

    
    
    //给pageControl添加事件
    [_pageControl addTarget:self action:@selector(handlePageCotrollerChangeAction:) forControlEvents:UIControlEventValueChanged];
    
    
    _firstLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 120, self.bounds.size.width, 20)];
    _firstLabel.font = [UIFont systemFontOfSize:12.0];
    _firstLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    _firstLabel.textColor = [UIColor whiteColor];
    _firstLabel.textAlignment = NSTextAlignmentCenter;
    _firstLabel.userInteractionEnabled = YES;
    [_firstImageView addSubview:_firstLabel];
    
    _secondLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 120, self.bounds.size.width, 20)];
    _secondLabel.font = [UIFont systemFontOfSize:12.0];
    _secondLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    _secondLabel.textColor = [UIColor whiteColor];
    _secondLabel.textAlignment = NSTextAlignmentCenter;
    _secondLabel.userInteractionEnabled = YES;
    [_secondImageView addSubview:_secondLabel];
    
    _thirdLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 120, self.bounds.size.width, 20)];
    _thirdLabel.font = [UIFont systemFontOfSize:12.0];
    _thirdLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    _thirdLabel.textColor = [UIColor whiteColor];
    _thirdLabel.textAlignment = NSTextAlignmentCenter;
    _thirdLabel.userInteractionEnabled = YES;
    [_thirdImageView addSubview:_thirdLabel];
    
    //计时器
    [self p_startTimer];
    
}

- (void)addTapGesture
{
    //遍历imageViewArray数组得到每个imageView对象
    for (UIImageView * view in self.imageViewArray) {
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTapGestureAction:)];
        //分别添加手势
        [view addGestureRecognizer:tap ];
        [tap release];
    }
}

//手势事件处理
- (void)handleTapGestureAction:(UITapGestureRecognizer *)tap
{
    //tap.view可以找到轻拍事件发上在那个视图上
     UIImageView * view = (UIImageView *)tap.view;
    //判断事件发生的那个视图的image是否为空（用于解决滚动视图还未加载时的崩溃）
    if (view.image != nil) {
        //遍历imageViewArray分别判断事件发生在哪个视图上
        for (int i = 0; i<self.imageViewArray.count; i++) {
            if (tap.view == self.imageViewArray[i]) {
                /*
                // UIImageView * view = (UIImageView *)tap.view;
                //HealthNews * news =(HealthNews *) self.healthNewsArray[i];
                //news.showImage = view.image;
                 */
                //找到后执行block回调（参数是controller传回对应的HealthNews对象）
                self.pushDetailViewBock(self.healthNewsArray[i]);
            }
        }
    }
    
   
}
- (void)setImageWithArray:(NSArray *)array
{
    
    self.healthNewsArray = array;
    for (int i = 0; i < self.imageViewArray.count; i++) {
//        HealthNews * news = (HealthNews *)array[i];
        HealthNews * news = array[i];
        UIImageView * imageView = self.imageViewArray[i];
        UILabel * label = [imageView.subviews lastObject];
        label.text = news.title;
        NSString * url = APIImageURL(news.img);
        
        [self.imageViewArray[i] sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:kPlaceholderImage completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            news.showImage = image;
        }];
//        [self.imageViewArray[i]  setImageWithURL:[NSURL URLWithString:url]success:^(UIImage *image, BOOL cached) {
//            news.showImage = image;
//        } failure:nil];
        
    }
    
//    HealthNews * news = (HealthNews *)array[0];
//    NSString * url = APIImageURL(news.img);
//    [self.firstImageView setImageWithURL:[NSURL URLWithString:url]];
//    
//    news =  (HealthNews *)array[1];
//    url = APIImageURL(news.img);
//    [self.secondImageView setImageWithURL:[NSURL URLWithString:url]];
//    
//    news = (HealthNews *)array[2];
//    url = APIImageURL(news.img);
//    [self.thirdImageView setImageWithURL:[NSURL URLWithString:url]];
    
}

//计时器
- (void)p_startTimer
{
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(p_setupTimeForScrollView) userInfo:nil repeats:YES];
}

#pragma mark -----------控制方法------------
//pageControl控制图片的改变
- (void)handlePageCotrollerChangeAction:(id)sender
{
    //    NSLog(@"%d",_pageControl.currentPage);
    //计算当前滚动到第几页 = 图片宽度*页码
    CGFloat offsetx = _pageControl.currentPage * _scrollView.frame.size.width;
    //切换动画效果
    [_scrollView setContentOffset:CGPointMake(offsetx, 0) animated:YES];
    
}
//代理方法，scrollView滑动近似停止时，pageControl的改变
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //移动到的页数
    NSInteger pageNumber = _scrollView.contentOffset.x / _scrollView.frame.size.width;
    //控制页面管理器
    _pageControl.currentPage = pageNumber;
    
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self p_startTimer];//开始
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self removeTimer];//结束
}
- (void)removeTimer
{
    NSLog(@"over");
    [self.timer invalidate];
    
}
//设置scrollView上图片自动滚动的时间间隔
- (void)p_setupTimeForScrollView
{
    int page=(int)_pageControl.currentPage;
    if (page==2) {
        page=0;
    }else{
        page++;
    }
    
    CGFloat offsetx = page * _scrollView.frame.size.width;
    _scrollView.contentOffset = CGPointMake(offsetx, 0);
    //切换动画效果

    
    
}

//滚动的时候调用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //NSLog(@"滚动中");
    if (scrollView == _scrollView) {
        CGFloat scroll = _scrollView.frame.size.width;
        CGFloat x = _scrollView.contentOffset.x;
        NSInteger page = (x + scroll/2)/scroll;
        _pageControl.currentPage = page;
    }
    
}


- (void)awakeFromNib
{
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
